import React, {memo, useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";

import "./status.css";
import Title from "../../../../../components/Title/Title";
import {ProtocolCanvas} from "../../../../../common/canvas";
import {saveData} from "../../../store/actionCreators";
import {deepClone, getCurrentTime} from "../../../../../common/utils";
import {AMPLIFICATION} from "../../../protocol/config";
import {saveExportObj, saveExportObjCn} from "../../../export/store/actionCreators";
import {saveCurrentPercent} from "../../store/actionCreators";
import {translateStausInfoCE, translateStausInfoEC} from "../../config";

export default memo(function Status() {
  const dispatch = useDispatch();
  const {exportObj, exportObjCn, isCN} = useSelector(state => ({
    exportObj: state.exportReducer.exportObj,
    exportObjCn: state.exportReducer.exportObjCn,
    isCN: state.languageReducer.isCN
  }));
  const {stages, runStart, experimentInfo, userInfo, data, machineStatus, machineWorkStatus} = useSelector(state => ({
    stages: state.protocolReducer.stages,
    runStart: state.runReducer.runStart,
    experimentInfo: state.experimentReducer.experimentInfo,
    userInfo: state.loginReducer.info,
    data: state.dataReducer.data,
    machineStatus: state.runReducer.machineStatus,
    machineWorkStatus: state.navigationReducer.machineWorkStatus
    // currentPercentRedux: state.runReducer.currentPercent
  }));
  const [experimentName, setExperimentName] = useState(data.experimentName);
  const [stages_, setStages_] = useState(data.protocol.stages);
  const [runModel, setRunModel] = useState(
    isCN ? data.runModeIsSample ? "标准/样本控温" : "快速/模块控温"
      : data.runModeIsSample ? "Standard/Sample Temperature" : "Fast/Block Temperature");
  let canvasStyle = {
    background: "#213040",
    stepSeparationLineColor: "#aaa",
    stageSeparationLineColor: "#aaa",
    lineColorRealtime: "#B78533",
    progressBarBorderColor: "#fff",
    lineColor: "#fff",
    temperatureColor: "#fff",
    titleColor: "#fff",
    progressBarColor: "#33BE94",
    widthLeft: 145,  //  width:930/stepNum - 10
    widthRight: 145,
    drawRealtime: true,
    maxY: 110,
    paddingLeft: 45,
    paddingTop: 100,
    paddingBottom: 10,
    paddingRight: 10,
    drawStageSeparationLineMode: true
  };

  useEffect(() => {
    console.log(experimentInfo);
    let flatArr = []; //  用于请求仪器数据时调用(有GOTO的占位,避免在请求仪器数据时出现数组越界 仪器的currentStep会多出一个GOTO)
    let canvasFlatArr = []; //  用于初始化run界面status canvas时调用
    stages_.forEach(stage => {
      flatArr.push(stage.steps);
      canvasFlatArr.push(stage.steps);
      stage.state === AMPLIFICATION && flatArr.push(false);       //  AMPLIFICATION有一个GOTO step,用false占位
    });
    flatArr = flatArr.flat();
    canvasFlatArr = canvasFlatArr.flat();
    let cameraArr = [],
      temperatureArr = [],
      titleArr = stages_.map(stage => stage.state),
      circleArr = stages_.map(stage => Number(stage.cycle)),
      stagesArr = stages_.map(stage => stage.steps.length),
      baseWidth = Math.floor((885 / flatArr.filter(item => item).length) / 2);
    canvasFlatArr.forEach((step, index) => {
      step.record && cameraArr.push(index);
      temperatureArr.push(step.temperature);
    });
    // console.log([stages_,flatArr]);
    let runTemperatureLine = ProtocolCanvas.init("runCanvas", {...canvasStyle, widthLeft: baseWidth, widthRight: baseWidth});
    runTemperatureLine.drawTemperatures([0, 20, 40, 60, 80, 100]);
    runTemperatureLine.draw(temperatureArr);
    runTemperatureLine.drawCamera(cameraArr);
    runTemperatureLine.drawTitle(titleArr);
    runTemperatureLine.setStages(stagesArr);
    runTemperatureLine.setCycles(circleArr);
    let [currentStep, currentText] = [machineStatus.currentStep, machineStatus.currentCycle];
    let currentTemperature = machineStatus.sampleTemperature && machineStatus.sampleTemperature[1] / 100;
    // let currentPercent = currentPercentRedux;
    //  如果实验中途退出页面在重进后会导致stages初始化,如果实验设置的stages比初始化的多会导致数组越界
    if (machineStatus.currentStep - 1 >= flatArr.length) {
      return;
    }
    let currentPercent = machineStatus.currentStep &&
      Math.abs(1 - Math.min(machineStatus.currentTimeRemain, flatArr[machineStatus.currentStep - 1].time) / flatArr[machineStatus.currentStep - 1].time); //  这里需要用到占位
    if (!runStart) {
      let endStep = 0;
      typeof currentStep === "number" && (endStep = flatArr.length);
      runTemperatureLine.drawCurrent({
        step: endStep,
        temperature: temperatureArr[temperatureArr.length],
        percent: 1,
        text: currentText
      });
    } else {
      runTemperatureLine.drawCurrent({
        step: currentStep,
        temperature: currentTemperature,
        percent: currentPercent,
        text: currentText
      });
      // dispatch(saveCurrentPercent(currentPercent));
    }
    //  设置Export对象
    setTimeout(() => {
      let cloneExportObj = {};
      cloneExportObj = deepClone(isCN ? exportObjCn : exportObj, cloneExportObj);
      if (document.getElementById("runCanvasImgUrl")) {
        cloneExportObj.protocol.imgProtocolGraph = document.getElementById("runCanvasImgUrl").toDataURL().split(",")[1];
      }
      isCN ? dispatch(saveExportObjCn(cloneExportObj))
        : dispatch(saveExportObj(cloneExportObj));
    });
    return () => {
      runTemperatureLine.destroyCanvas();
    };
  }, [runStart, machineStatus]);

  function reNew() {
    if (runStart) {
      return;
    }
    let name = getCurrentTime();
    dispatch(saveData({...data, experimentName: name}));
    setExperimentName(name);
  }

  return (
    <div className="runPageStatus">
      <section id="runCanvas"/>
      <section>
        <Title name={isCN ? "基本信息" : "Summary"} btn={isCN ? "刷新" : "Renew"} btnAction={reNew}/>
        <div>
          <div>
            <div>{isCN ? "实验名称" : "Experiment Name"}</div>
            <input type="text" key={experimentName} defaultValue={experimentName}
                   readOnly={runStart}
                   onBlur={e => dispatch(saveData({...data, experimentName: e.target.value}))}
                   onKeyUp={e => e.target.value = e.target.value.replace(/[\u0391-\uFFE5]/gi, '')}
            />
          </div>
          <div>
            <div>{isCN ? "条形码" : "Barcode"}</div>
            <input type="text" defaultValue={data.barcode}
                   onBlur={e => dispatch(saveData({...data, barcode: e.target.value}))}
            />
          </div>
          <div>
            <div>{isCN ? "用户名" : "User Name"}</div>
            <input type="text" readOnly={true} value={userInfo.username}/>
          </div>
          <div>
            <div>{isCN ? "实验类型" : "Experiment Identify"}</div>
            <input type="text" readOnly={true} value={isCN ? translateStausInfoEC(data.experimentIdentity) : translateStausInfoCE(data.experimentIdentity)}/>
          </div>
          <div>
            <div>{isCN ? "试剂类型" : "Reagents Type"}</div>
            <input type="text" readOnly={true} value={isCN ? translateStausInfoEC(data.reagentsType) : translateStausInfoCE(data.reagentsType)}/>
          </div>
        </div>
        <div>
          <div style={{height: 130}}>
            <div style={{float: "none"}}>{isCN ? "备注" : "Comments"}</div>
            <textarea defaultValue={data.comments}
                      onBlur={e => dispatch(saveData({...data, comments: e.target.value}))}
            />
          </div>
          <div>
            <div>{isCN ? "运行模式" : "Run Mode"}</div>
            <input type="text" readOnly={true} value={runModel}/>
          </div>
          <div>
            <div>{isCN ? "反应体积" : "Reaction Volume"}</div>
            <input type="text" style={{textAlign: "center"}} readOnly={true} value={data.reactionVolume}/>
          </div>
        </div>
      </section>
    </div>
  );
});